<template>
  <div>
    <el-form ref="form" label-width="100px" :model="item" :key="groupedIndex">
      <div v-if="item.questions.length != 0">
        <el-tag>{{ item.rootName }}</el-tag>
        <el-button
          size="mini"
          style="float: right"
          :class="
            showAllScores[groupedIndex].showAllScore == true ? 'active' : ''
          "
          @click="
            showAllScores[groupedIndex].showAllScore = !showAllScores[
              groupedIndex
            ].showAllScore
          "
        >
          设置统一分数
        </el-button>
        <el-form-item>
          <div class="bigQuestionName">
            <div class="allScore">
              <el-input-number
                v-model="item.score"
                :precision="2"
                :step="0.1"
                :min="0.1"
                v-if="showAllScores[groupedIndex].showAllScore"
                @change="setAllScore($event, groupedIndex)"
                @blur="showAllScores[groupedIndex].showAllScore = false"
                placeholder="请输入分数"
              ></el-input-number>
              <!-- v-model="examData.item.score" -->
            </div>
          </div>
        </el-form-item>
      </div>
      <div
        v-for="(question, questionIndex) in item.questions"
        :key="questionIndex"
      >
        <div class="ql-snow">
          <div class="ql-editor" v-if="isData(question.questionTopic)">
            <el-card>
              <el-input
                class="ql-font-Segoe-UI ql-size-18px"
                v-model="question.questionTopic[0]"
                v-html="question.questionTopic[0]"
                @click.native="
                  inputClick(
                    question.questionTopic[0],
                    groupedIndex,
                    questionIndex,
                    -3
                  )
                "
              ></el-input>
            </el-card>
            <el-form-item class="topic-content">
              <span slot="label"  style="position: relative; top: 85px">
                <el-tag>
                  {{ getPrefix(groupedIndex, questionIndex) }}
                </el-tag>
              </span>
              <el-row>
                <el-col :span="19">
                  <div class="ql-editor" style="position: relative; top: 40px">
                    <el-input
                      v-model="question.questionTopic[1]"
                      v-html="question.questionTopic[1]"
                      class="ql-font-Segoe-UI ql-size-18px"
                      @click.native="
                        inputClick(
                          question.questionTopic[1],
                          groupedIndex,
                          questionIndex,
                          -2
                        )
                      "
                    />
                  </div>
                </el-col>
                <el-col :span="5" class="ql-editor">
                  <el-cascader
                    v-model="question.path"
                    :options="item.typeList"
                    @change="
                      questionTypeChange($event, groupedIndex, questionIndex)
                    "
                    :props="{ value: 'id', label: 'typeName' }"
                    placeholder="请选择试题分类"
                  ></el-cascader>
                </el-col>
              </el-row>
            </el-form-item>
          </div>
          <el-form-item class="topic-content" v-else>
            <span slot="label" style="position: relative; top: 5px">
              <el-tag>
                {{ getPrefix(groupedIndex, questionIndex) }}
              </el-tag>
            </span>
            <el-row>
              <el-col :span="19">
                <div class="ql-editor">
                  <el-input
                    v-model="question.questionTopic"
                    v-html="question.questionTopic"
                    class="ql-font-Segoe-UI ql-size-18px"
                    @click.native="
                      inputClick(
                        question.questionTopic,
                        groupedIndex,
                        questionIndex,
                        -1
                      )
                    "
                  />
                </div>
              </el-col>
              <el-col :span="5" class="ql-editor">
                <el-cascader
                  v-model="question.path"
                  :options="item.typeList"
                  @change="
                    questionTypeChange($event, groupedIndex, questionIndex)
                  "
                  :props="{ value: 'id', label: 'typeName' }"
                  placeholder="请选择试题分类"
                ></el-cascader>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item
            v-for="(prefix, choiceIndex) in prefixs"
            :key="choiceIndex"
          >
            <span slot="label">
              <el-tag
                type="primary"
                style="border-radius: 100px; position: relative; top: 5px"
                >{{ prefix }}</el-tag
              >
            </span>
            <div class="ql-editor">
              <el-input
                @click.native="
                  inputClick(
                    question.choice[choiceIndex],
                    groupedIndex,
                    questionIndex,
                    choiceIndex
                  )
                "
                v-model="question.choice[choiceIndex]"
                v-html="question.choice[choiceIndex]"
                class="ql-font-Segoe-UI ql-size-18px"
              />
            </div>
          </el-form-item>
          <el-form-item>
            <span slot="label">
              <el-tag> 答案 </el-tag>
            </span>
            <el-radio-group v-model="question.answer">
              <el-radio
                v-for="(prefix, prefixIndex) in prefixs"
                :key="prefixIndex"
                :label="prefix"
                :border="true"
                >{{ prefix }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <span slot="label" style="position: relative; top: 5px">
              <el-tag>解析</el-tag>
            </span>
            <div class="ql-editor">
              <el-input
                v-model="question.analysis"
                v-html="question.analysis"
                @click.native="
                  inputClick(question.analysis, groupedIndex, questionIndex, 4)
                "
                class="ql-font-Segoe-UI ql-size-18px"
              />
            </div>
          </el-form-item>
          <el-form-item>
            <span slot="label">
              <el-tag>分数</el-tag>
            </span>
            <el-tag type="info">{{ question.score }}</el-tag>
          </el-form-item>
          <hr
            style="
              filter: progid:DXImageTransform.Microsoft.Shadow(color:#987cb9,direction:145,strength:15);
            "
            width="100%"
            color="#987cb9"
            SIZE="1"
          />
        </div>
      </div>
    </el-form>
    <el-dialog
      :visible.sync="myEditor.dialogVisible"
      :close-on-click-modal="false"
      append-to-body
      style="width: 100%; height: 100%"
      :show-close="false"
      center
    >
      <span slot="footer" class="dialog-footer">
        <quill-editor
          v-model="myEditor.content"
          ref="myQuillEditor"
          :options="editorOption"
        ></quill-editor>
        <el-button type="primary" @click="editorConfirm">确 定</el-button>
        <el-button @click="myEditor.dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor";
import * as Quill from "quill";

export default {
  components: {
    quillEditor,
  },
  props: ["groupedIndex", "item", "prefixIndex"],
  mounted() {
    //  自定义粘贴图片功能
    let quill = this.$refs.myQuillEditor.quill;
    this.$forceUpdate();
    quill.root.addEventListener(
      "paste",
      (evt) => {
        if (
          evt.clipboardData &&
          evt.clipboardData.files &&
          evt.clipboardData.files.length
        ) {
          evt.preventDefault();
          [].forEach.call(evt.clipboardData.files, (file) => {
            if (!file.type.match(/^image\/(gif|jpe?g|a?png|bmp)/i)) {
              return;
            }
            const formData = new FormData();
            formData.append("file", file);
            this.$http({
              url: this.$http.adornUrl(`/exam/exam/upload/picture`),
              method: "post",
              data: formData,
            }).then(({ data }) => {
              if (data && data.code === 0) {
                let length = quill.getSelection().index; //光标位置
                // 插入图片  图片地址
                quill.insertEmbed(length, "image", data.url);
                // 调整光标到最后
                quill.setSelection(length + 1); //光标后移一位
              } else {
                this.$message.error(data.msg);
              }
            });
          });
        }
      },
      false
    );
  },
  methods: {
    questionTypeChange(value, groupedIndex, questionIndex) {
      let id = value[value.length - 1];
      this.item.questions[questionIndex].typeId = id;
    },
    inputClick(content, groupedIndex, questionIndex, judgeIndex) {
      this.myEditor.groupedIndex = groupedIndex;
      this.myEditor.questionIndex = questionIndex;
      this.myEditor.judgeIndex = judgeIndex;
      this.myEditor.content = content;
      this.myEditor.dialogVisible = true;
    },
    isData(questionTopic) {
      if (questionTopic instanceof Array) {
        return true;
      }
      return false;
    },
    setAllScore(val, groupedIndex) {
      val = parseFloat(val);
      this.item.questions.forEach((item) => {
        item.score = val;
      });
    },
    //题目前缀(计算题号)
    getPrefix(groupedIndex, questionIndex) {
      let index = this.topicNavIndex_mixin(groupedIndex, questionIndex);
      this.item.questions[questionIndex].sort = index;
      index += this.prefixIndex;
      return "第" + index + "题";
    },
    topicNavIndex_mixin(groupedIndex, questionIndex) {
      let navIndex = 0;
      return navIndex + questionIndex + 1;
    },
    //点击编辑框中确认按钮事件
    editorConfirm() {
      this.myEditor.dialogVisible = false;
      let content = this.myEditor.content;
      console.log(content);
      if (!content) {
        return;
      }
      let groupedIndex = this.myEditor.groupedIndex;
      let questionIndex = this.myEditor.questionIndex;
      let judgeIndex = this.myEditor.judgeIndex;
      if (judgeIndex == -3) {
        if (content.indexOf("【资料】") == -1) {
          this.item.questions[questionIndex].questionTopic =
            content + this.item.questions[questionIndex].questionTopic[1];
        } else {
          this.item.questions[questionIndex].questionTopic[0] = content;
        }
      } else if (judgeIndex == -2) {
        this.item.questions[questionIndex].questionTopic[1] = content;
      } else if (judgeIndex == -1) {
        if (content.indexOf("【资料】") != -1) {
          content = content.replace(new RegExp("【资料】", "g"), "");
          this.item.questions[questionIndex].questionTopic = [
            "【资料】点击编辑资料",
            "" + content,
          ];
        } else {
          this.item.questions[questionIndex].questionTopic = content;
        }
      } else if (judgeIndex >= 0 && judgeIndex <= 3) {
        this.item.questions[questionIndex].choice[judgeIndex] = content;
      } else if (judgeIndex == 4) {
        this.item.questions[questionIndex].analysis = content;
      }
    },
  },
  data() {
    //quill编辑器的字体
    var fonts = [
      "SimSun",
      "SimHei",
      "Microsoft-YaHei",
      "KaiTi",
      "FangSong",
      "Arial",
      "Times-New-Roman",
      "sans-serif",
      "Segoe-UI",
    ];
    var Font = Quill.import("formats/font");
    Font.whitelist = fonts; //将字体加入到白名单
    Quill.register(Font, true);
    // 自定义字号的大小
    var sizes = [false, "16px", "18px", "20px", "22px", "26px", "28px", "30px"];
    var Size = Quill.import("formats/size");
    Size.whitelist = sizes;
    const toolbarOptions = [
      ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
      // ["blockquote", "code-block"], // 引用  代码块
      // [{ header: 1 }, { header: 2 }], // 1、2 级标题
      // [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
      [{ script: "sub" }, { script: "super" }], // 上标/下标
      [{ indent: "-1" }, { indent: "+1" }], // 缩进
      // // [{'direction': 'rtl'}],                         // 文本方向
      [{ size: sizes }], // 字体大小
      // [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
      // [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
      [{ font: fonts }], // 字体种类
      // [{ align: [] }], // 对齐方式
      ["clean"], // 清除文本格式
      // ["image"], // 链接、图片、视频
    ];
    return {
      prefixs: ["A", "B", "C", "D"],
      myEditor: {
        dialogVisible: false,
        groupedIndex: -1,
        questionIndex: -1,
        judgeIndex: -2,
        content: "",
      },
      //富文本编辑器配置
      editorOption: {
        placeholder: "",
        theme: "snow", // or 'bubble'
        modules: {
          toolbar: {
            container: toolbarOptions,
            // container: "#toolbar",
            handlers: {
              // image: function (value) {
              //   if (value) {
              //     // 触发input框选择图片文件
              //     this.$http({
              //       url: this.$http.adornUrl("/exam/exam/upload/picture"),
              //       method: "post",
              //       data: this.$http.adornData({
              //         "file": value
              //       })
              //     }).then(({ data }) => {
              //       if (data && data.code === 0) {
              //         this.$message.success(data.msg);
              //       } else {
              //         this.$message.error(data.msg);
              //       }
              //     });
              //   } else {
              //     this.quill.format("image", false);
              //   }
              // },
            },
          },
        },
      },
      showAllScores: [
        {
          id: 0,
          showAllScore: false,
        },
        {
          id: 1,
          showAllScore: false,
        },
        {
          id: 2,
          showAllScore: false,
        },
        {
          id: 3,
          showAllScore: false,
        },
        {
          id: 4,
          showAllScore: false,
        },
      ],
    };
  },
};
</script>

<style scoped>
</style>
